<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            html {
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="../libs/jszip.min.js"></script>
        <script src="../libs/docx-preview.js"></script>
        <script>
            window.addEventListener("message", (event) => {
                const { type, data,flag } = event.data || {};
                if (!type) {
                    return;
                }

                if (type === "docxPreview") {
                    if (!data) return;
                    const container = document.getElementById("container");
                    docx.renderAsync(data, container).then((res) => {
                        const tables =
                            container.querySelectorAll(".docx table");
                        for (const item of tables || []) {
                            const p = item.parentNode;
                            if (!p) {
                                continue;
                            }
                            const nextSibling = item.nextSibling;
                            p.removeChild(item);
                            const div = document.createElement("div");
                            div.style.width = "100%";
                            div.style.overflow = "auto";
                            div.appendChild(item);
                            p.insertBefore(div, nextSibling);
                        }
                        window.parent.postMessage(
                            {
                                type: "docxPreview",
                                data: "done",
                            },
                            "*"
                        );
                    });
                }

                if (type === "getDocxContent") {
                    if (!data) return;
                    const container = document.getElementById("container");
                    docx.renderAsync(data, container).then((res) => {
                        window.parent.postMessage(
                            {
                                type: "getDocxContent",
                                flag: flag,
                                data: container.getElementsByClassName('docx-wrapper')[0].innerText,
                            },
                            "*"
                        );
                    });
                }
            });
        </script>
    </body>
</html>
